package enterprise.manage.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: lihongya
 * Date: 2010-4-29
 * Time: 10:01:33
 * Desc:  展示图片
 */
public class GetImgFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        String beginPath = "D:\\";

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String url = httpServletRequest.getRequestURL().toString();
        url = url == null ? "" : url.replace("\r","\\r").replace("\n","\\n");
        int i_begin = url.indexOf("upload");
        String str = url.substring(i_begin);
//        str.replaceAll("/", "\\");

        str = beginPath + str;

        File file = new File(str);
        ByteArrayOutputStream out;
        if (file.exists()) {
            FileInputStream stream = new FileInputStream(file);
            out = new ByteArrayOutputStream(1000);

            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            stream.close();
            out.close();
            servletResponse.getOutputStream().write(out.toByteArray());
        }

    }

    @Override
    public void destroy() {
    }
}

